<template>
  <el-dialog :title="title" :visible="visible" @close="close">
    <el-form label-width="120px">
      <el-form-item label="名称">
        <el-input v-model="dict.dictname"></el-input>
      </el-form-item>

      <el-form-item label="上级">
        <dict-tree ref="dicttree" :hidden="dict.id!==undefined" @change="chgparent"></dict-tree>
      </el-form-item>

      <el-form-item label="排序">
        <el-input-number v-model="dict.sorts" :min="1" label="排序" style="margin-left: 20px;"></el-input-number>
      </el-form-item>

      <el-form-item label="说明">
        <el-input v-model="dict.note" :rows="3" style="width: 60%;margin-left: 20px;" type="textarea"></el-input>
      </el-form-item>


      <div class="btn">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="info" @click="close">取消</el-button>
      </div>

    </el-form>
  </el-dialog>
</template>

<script>
const DictTree = () => import('./DictTree.vue')
export default {
  data() {
    return {
      dict: {
        dictname: "",
        sorts: "",
        parentid: "",
        note: "",
        euid: ""
      },
      name: "",
      parentName: ""
    }
  },
  components: {
    DictTree
  },
  computed: {
    title() {
      return this.name + "编辑";
    },
    parent() {
      if (this.parentName === "")
        return this.name;
      return this.parentName;
    }
  },

  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },

  methods: {

    chgparent($event) {
      this.dict.parentid = $event.id;
    },
    //显示当前dialog时调用的初始化方法
    init(data, pid, name) {
      this.name = name;
      const tmp = this.$session.getUser();
      if (data === undefined) {
        //说明是新增
        this.dict = {
          dictname: "",
          sorts: "",
          parentid: pid,
          note: "",
          euid: tmp.euid
        }
      } else {
        //说明是修改
        this.dict = data;
      }

      this.$nextTick(() => {
        this.$refs.dicttree.init(pid, name);
      })

    },

    close() {
      this.$emit("update:visible", false);
    },
    save() {

      let promise;
      if (this.dict.id) {
        //如果用户id存在 说明是修改
        promise = this.$api.updateDict(this.dict);
      } else {
        promise = this.$api.saveDict(this.dict);
      }

      //处理结果
      promise.then(res => {
        if (res.code === 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
          this.close();
          //刷新数据
          this.$emit("refreshData");
        }
      })
    }
  }
}
</script>

<style scoped>
.btn {
  text-align: center;
  margin-top: 30px;
}

.btn button {
  margin-left: 50px;
}

.el-input {
  width: 60%;
  margin-left: 20px;
}

.pwd {
  color: #999;
  font-size: 14px;
  margin-left: 10px;
}
</style>
